package aparicio.mbox.parse;

import java.util.ArrayList;
import java.util.List;

/**The base class needed for parsing email files.
 * 
 * @author Trevor
 */
public class EmailParser {
	
	private String[] _files;
	private List<Email> _emails; // a list of parsed emails
		
	/**Basic EmailParser constructor.
	 * 
	 * @param files An array of Strings that define where the files can be found on the file system
	 */
	public EmailParser(String[] files) {
		_files = files;
		_emails = new ArrayList<Email>();
	}
	
	/**Parse all of the email files given in the preliminary argument.
	 * 
	 * @throws Exception
	 */
	public void parseAll() throws Exception {
		if (_files.length == 0) {
			System.out.println("EmailParser.parseAll() failed: No email files to parse");
			throw new Exception("No email files to parse");
		}
		
		for (String file: _files) {
			if (file.contains(".mbox")) {
				try {
					parseMbox(file);
				} catch (Exception e) {
					System.out.println("EmailParser.parseAll() failed");
					throw e;
				}
			}
		}
	}

	/**Parse an mbox email file.
	 * 
	 * @param file The String the describes where the file to parse is located on the file system
	 * 
	 * @throws Exception
	 */
	private void parseMbox(String file) throws Exception {
		MboxFile mbox = new MboxFile(file);
		try {
			mbox.parse();
		} catch (Exception e) {
			System.out.println("EmailParser.parseMbox() failed");
			throw e;
		}
		
		// add the parsed email to the list of parsed emails
		_emails.add(mbox);
	}
	
	/**Print the statistics of the email after the file has been parsed.
	 * 
	 * @throws Exception
	 */
	public void printStats() throws Exception {
		for (Email email: _emails) {
			try {
				email.printStats();
			} catch (Exception e) {
				System.out.println("EmailParser.printStats() failed");
				throw e;
			}
		}
	}
}
